package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ClassName: ChannelController
 * Description:
 *
 * @Author linz
 * @Creat 2025/3/15 9:47
 * @Version 1.00
 */
@RestController
@RequestMapping("/channel")
@Tag(name="聚合数据")
@Slf4j
public class ChannelController extends BaseController {
    @Autowired
    private ProductSkuService productSkuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;

    @Autowired
    private SkuStockService skuStockService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductDetailsService productDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/index")
    @Operation(summary = "获取首页数据")
    public AjaxResult index(){

        //获取商品skuVO列表
        List<ProductSkuVo> topSaleList = productSkuService.getTopSaleList();
        //获取商品一级分类VO列表
       List<CategoryVo> levelOneCategoryList = categoryService.getLevelOneCategory();

       IndexVo indexVo = new IndexVo();
       indexVo.setProductSkuList(topSaleList);
       indexVo.setCategoryList(levelOneCategoryList);

       return success(indexVo);
    }

    @Operation(summary = "获取分类嵌套列表")
    @GetMapping( "/category")
    public AjaxResult category() {
        return success(categoryService.tree());
    }

    @Operation(summary = "显示商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @Parameter(description = "当前页码")
            @PathVariable Integer pageNum,

            @Parameter(description = "每页记录数")
            @PathVariable Integer pageSize,

            SkuQuery skuQuery) {

        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> list = productSkuService.selectProductSkuList(skuQuery);
        return getDataTable(list);
    }

    @Operation(summary = "获取全部品牌")
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return success(brandService.list());
    }

    @Operation(summary = "商品详情")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(
            @Parameter(description = "skuId")
            @PathVariable Long skuId) {


        //从bitmap中查询是否有对应id
        String bitmapKey ="product:sku:data";
        Boolean hasSku = redisTemplate.opsForValue().getBit(bitmapKey, skuId);
        if(!hasSku){
            log.info("商品不存在");
            throw new ServiceException("商品不存在");
        }
        ItemVo itemVo = new ItemVo();

        //*************************************************************************

        /**
         * 创建异步编排任务
         * supplyAsync：执行一个异步任务并且有返回结果
         */
        CompletableFuture<Long> futureProductSku = CompletableFuture.supplyAsync(() -> {
            //获取sku信息
            ProductSku productSku = productSkuService.getProductSkuById(skuId);
            itemVo.setProductSku(productSku);
            //获取商品id
            Long productId = productSku.getProductId();
            return productId;
        },threadPoolExecutor);

        CompletableFuture<Void> futureSkuPrice = CompletableFuture.runAsync(() -> {
            //获取商品最新价格
            SkuPriceVo skuPrice = productSkuService.getSkuPrice(skuId);
            itemVo.setSkuPrice(skuPrice);
        }, threadPoolExecutor);

        CompletableFuture<Void> futureSkuStock = CompletableFuture.runAsync(() -> {
            //获取商品库存信息
            SkuStockVo skuStock = skuStockService.getSkuStock(skuId);
            itemVo.setSkuStock(skuStock);
        }, threadPoolExecutor);

        CompletableFuture<Product> futureProduct = futureProductSku.thenApply(productId -> {
            //获取商品信息
            Product product = productService.getById(productId);
            return product;
        });

        CompletableFuture<Void> futureDetailsImageUrlList = futureProductSku.thenAccept(productId -> {
            //获取商品详情图片
            String[] detailsImageUrlList = productDetailsService.getProductDetails(productId);
            itemVo.setDetailsImageUrlList(detailsImageUrlList);
        });


        CompletableFuture<Void> futureSkuSpecValueMap = futureProductSku.thenAccept(productId -> {
            //获取商品规格Map
            Map<String, Long> skuSpecValueMap = productSkuService.getSkuSpecValue(productId);
            itemVo.setSkuSpecValueMap(skuSpecValueMap);
        });


        CompletableFuture<Void> futureSpecValueList = futureProduct.thenAccept(product -> {
            //商品信息:商品规格列表
            JSONArray specValueList = JSON.parseArray(product.getSpecValue());
            itemVo.setSpecValueList(specValueList);
        });

        CompletableFuture<Void> futureSliderUrlList = futureProduct.thenAccept(product -> {
            //获取商品轮播图
            String[] sliderUrlList = product.getSliderUrls().split(",");
            itemVo.setSliderUrlList(sliderUrlList);
        });


        // 等待所有异步任务完成，并捕获异常
        CompletableFuture
                .allOf(futureProductSku,
                        futureSkuPrice,
                        futureSkuStock,
                        futureProduct,
                        futureDetailsImageUrlList,
                        futureSkuSpecValueMap,
                        futureSpecValueList,
                        futureSliderUrlList)
                .join();


        return success(itemVo);
    }
}
